package com.appspot.zarm.controller.operations;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.appspot.zarm.controller.GameAction;
import com.appspot.zarm.controller.GameActionFactory;
import com.appspot.zarm.controller.GameActionResult;
import com.appspot.zarm.controller.RequestParameters;
import com.appspot.zarm.controller.user.User;
import com.appspot.zarm.controller.user.UserFactory;
import com.appspot.zarm.controller.user.UserType;
import com.appspot.zarm.game.GamesStorage;
import com.appspot.zarm.transfer.Transferer;

public class GameOperation extends Operation {

	private final static String USER_ATTR = "user";
	
	public GameOperation(ServletContext servletContext) {
		super(servletContext);
	}

	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response) {
		
		// action and game data
		String action = (String) request.getParameter(RequestParameters.ACTION_PARAM);
		String rawData = (String) request.getParameter(RequestParameters.DATA_PARAM);
		boolean isMultiplayer = (String) request.getParameter(RequestParameters.MULTIPLAYER_PARAM) != null;

		// join second player to existing game
		String counterUserId = (String) request.getParameter(RequestParameters.JOIN_ID_PARAM);
		
		// action processing
		if (action != null) {
			
			HttpSession session = request.getSession();
			User user = (User) session.getAttribute(USER_ATTR);
			
			if (user == null){
				String userId = session.getId();
				user = new UserFactory().newUser(UserType.SESSION, userId);
				session.setAttribute(USER_ATTR, user);
			}
			
			GamesStorage gamesStorage = getGamesStorage();
			
			User counterUser = null;
			
			if (counterUserId != null){
				counterUser = new UserFactory().newUser(UserType.SESSION, counterUserId);
			}
			
			GameAction gameAction = new GameActionFactory().getGameAction(GameActionFactory.GOMOKU, gamesStorage);
			Transferer transferer = gameAction.newTransferer("json");
			Object data = transferer.transfer(rawData);
			GameActionResult result = gameAction.process(user, action, data, isMultiplayer, counterUser);
			
			String outData = transferer.transfer( result.getData() );
			
			// return result to the callback javascript method
			if (GameAction.START_ACTION.equals(action) || GameAction.JOIN_ACTION.equals(action) ) {
				goLayoutPage(request, response);
			} else {
				print(response, outData);
			}

		} else {
			// action is absent so only refresh layout page 
			goLayoutPage(request, response);
		}		
	}

}
